import os
from multiprocessing import Process, Queue
import time


def func():
    for i in range(3):
        print(i)

def func2(param1,param2):
    print(param1,param2)

if __name__ == '__main__':
    #实例化进程对象,目标执行函数
    process = Process(target=func)
    # 运行process进程
    process.start()
    # 在主线程执行函数
    func()

# args:根据元组中的索引对应函数接受的参数
# kwargs:根据字典中的key对应函数接受的参数
# if __name__ == '__main__':
#     process1 = Process(target=func2,args=('value1','value2'))
#     process1.start()
#     process2 = Process(target=func2,kwargs={'param1':'value1','param2':'value2'})
#     process2.start()


from multiprocessing import Process
import time # 用于延时

# 子进程运行的目标方法
def func3():
    for i in range(10000):
        print(i)
        time.sleep(1)

# if __name__ == '__main__':
#     process = Process(
#                     target=func3,
#                     name='子进程1', # 1.name 为进程起别名
#                 )
#     # 2.start 运行进程
#     process.start()
#     # 3.pid 得到子进程的pid
#     print('子进程的pid=',process.pid)
#     # 4.is_alive() 判断进程是否正在运行
#     print(process.is_alive())
#     # 5.join() 堵塞主进程
#     process.join(timeout=2)
#     # 6.terminate() 停止子进程
#     process.terminate()


def func4():
    print('子进程的pid=',os.getpid())
    print('子进程的ppid=',os.getppid())

# if __name__ == '__main__':
#     process = Process(target=func4)
#     process.start()
#     print('process的pid=',process.pid)
#     print('主进程的pid=',os.getppid())

# 1.定义类对象，继承Process
class MyProcess(Process):
    def __init__(self,param):
        # 2.1 调用父类的init方法
        Process.__init__(self)
        # 2.2 处理接受参数
        self.param = param
    # 3. 定义run方法（相当于进程执行的目标方法）
    def run(self):
        print(self.param)

# if __name__ == '__main__':
    # # 4.1 实例化类对象
    # myProcess = MyProcess('value')
    # myProcess.start()

# 2.进程目标函数需要接受队列
def func5(q):
    while True:
        print(q.get())

# if __name__ == '__main__':
#     # 3.实例化进程通信队列
#     queue = Queue()
#     # 4.传递队列
#     Process(target=func5,args=(queue,)).start()
#     # 5.队列通信例子：
#     import time
#     for i in range(5):
#         queue.put(i)
#         time.sleep(1)